package com.ruoyi.wlw.socket;

import org.springframework.stereotype.Service;

import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 水电连接socket服务端
 */
@Service
public class WaterAndElectricitySocketService  {


//    @Override
//    public void run() {
//        this.publishServer(11001);
//    }
public static void main(String[] args) {
    publishServer(11001);
}
    private static BufferedReader reader;
    private static ServerSocket serverSocket;
    private static Socket socket;
    /**
     * 发布tcp服务端
     * @param port 服务端口
     */
    public static void publishServer(int port){
        try {
            serverSocket = new ServerSocket(port);        //实例化服务端socket
            System.out.println("服务器套接字已经创建成功");
            System.out.println(((InetSocketAddress)serverSocket.getLocalSocketAddress()).getAddress().getHostAddress());
            System.out.println("InetAddress.getLocalHost().getHostAddress() = " + InetAddress.getLocalHost().getHostAddress());
            while (true) {
                System.out.println("等待客户机的连接:");
                socket = serverSocket.accept();        //实例化socket对象
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));    //实例化BufferReader对象
                getClientMessage();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void getClientMessage() {
        try {
            String message = null;
            while ((message = reader.readLine())!=null) {
                System.out.println("客户机传来的信息是："+message);
                OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream(),"UTF-8");
                // PrintWriter out = new PrintWriter(osw,);
                PrintWriter  pw = new PrintWriter(osw,true);
                pw.println("服务端已接收");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
